package cn.school.system.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import cn.school.common.constant.enums.DataStatusEnum;
import cn.school.common.constant.enums.OrderTypeEnum;
import cn.school.common.constant.enums.PayStatusEnum;
import cn.school.common.utils.StringUtils;
import cn.school.common.utils.sign.Md5Utils;
import cn.school.system.config.FriendsConfig;
import cn.school.system.domain.*;
import cn.school.system.model.req.CreateOrderDTO;
import cn.school.system.model.resp.CountInfoRespDTO;
import cn.school.system.model.resp.CreateOrderRespDTO;
import cn.school.system.service.*;
import cn.school.system.service.pay.WxPayService;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.school.system.mapper.BiOrderInfoMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单信息Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-15
 */
@Service
public class BiOrderInfoServiceImpl implements IBiOrderInfoService
{
    @Autowired
    private BiOrderInfoMapper biOrderInfoMapper;
    @Autowired
    private IBiGoodService biGoodService;
    @Autowired
    private IBiPaperService biPaperService;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private IBiShopService biShopService;
    @Autowired
    private IBiWxUserService wxUserService;
    @Autowired
    private FriendsConfig friendsConfig;

    /**
     * 查询订单信息
     *
     * @param id 订单信息主键
     * @return 订单信息
     */
    @Override
    public BiOrderInfo selectBiOrderInfoById(Long id)
    {
        return biOrderInfoMapper.selectBiOrderInfoById(id);
    }

    /**
     * 查询订单信息列表
     *
     * @param biOrderInfo 订单信息
     * @return 订单信息
     */
    @Override
    public List<BiOrderInfo> selectBiOrderInfoList(BiOrderInfo biOrderInfo)
    {
        return biOrderInfoMapper.selectBiOrderInfoList(biOrderInfo);
    }

    /**
     * 新增订单信息
     *
     * @param biOrderInfo 订单信息
     * @return 结果
     */
    @Override
    public int insertBiOrderInfo(BiOrderInfo biOrderInfo)
    {
        biOrderInfo.setCreateTime(new Date());
        return biOrderInfoMapper.insertBiOrderInfo(biOrderInfo);
    }

    /**
     * 修改订单信息
     *
     * @param biOrderInfo 订单信息
     * @return 结果
     */
    @Override
    public int updateBiOrderInfo(BiOrderInfo biOrderInfo)
    {
        return biOrderInfoMapper.updateBiOrderInfo(biOrderInfo);
    }

    /**
     * 批量删除订单信息
     *
     * @param ids 需要删除的订单信息主键
     * @return 结果
     */
    @Override
    public int deleteBiOrderInfoByIds(Long[] ids)
    {
        return biOrderInfoMapper.deleteBiOrderInfoByIds(ids);
    }

    /**
     * 删除订单信息信息
     *
     * @param id 订单信息主键
     * @return 结果
     */
    @Override
    public int deleteBiOrderInfoById(Long id)
    {
        return biOrderInfoMapper.deleteBiOrderInfoById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public CreateOrderRespDTO save(CreateOrderDTO dto) throws Exception {
        BiGood good = biGoodService.findByGoodCode(dto.getGoodCode());
        if(good==null){
            throw new Exception("产品信息错误");
        }

        boolean payFlag = true;
        BiOrderInfo oi = new BiOrderInfo();

        if(dto.getPaper()!=null){
            BiPaper paper = dto.getPaper();

            if(StringUtils.isEmpty(paper.getWxNumber())){
                throw new Exception("微信号必填");
            }

            //判断是否不需要支付
            if(paper.getGender()==2){
                Long num = biPaperService.findByOpneidCount(paper.getOpenid());
                if(num==null){
                    num = 0L;
                }
                if(num.intValue()<1){
                    payFlag = false;
                    paper.setStatus(DataStatusEnum.USABLE.getStatus());
                }
            }

            if(paper.getStatus()==null || paper.getStatus()!=DataStatusEnum.USABLE.getStatus()){
                paper.setStatus(DataStatusEnum.WAIT_PASS.getStatus());
            }

            biPaperService.insertBiPaper(paper);
            oi.setPaperId(paper.getId());
        }

        BiWxUser temp = new BiWxUser();
        temp.setOpenid(dto.getOpenid());
        List<BiWxUser> wxUserList = wxUserService.selectBiWxUserList(temp);

        if(wxUserList!=null && wxUserList.size()>0) {
            BiWxUser wxUser = wxUserList.get(0);
            //假如推荐店铺ID不为空
            if (wxUser != null && wxUser.getParentShopId() != null) {
                BiShop shop = biShopService.selectBiShopById(wxUser.getParentShopId());
                oi.setRecommendShopId(shop.getId());
                oi.setRecommendShopPhone(shop.getPhone());
            }
        }


        oi.setCqSchoolId(dto.getCqSchoolId());
        //微信openid
        oi.setOpenid(dto.getOpenid());
        //订单类型 1-添加，2-抽取，3-开通店铺
        oi.setOrderType(dto.getOrderType());
        //商户支付单号、订单号
        oi.setMchPayOrderNo(getOrderNo(dto.getOpenid()));
        //是否支付
        oi.setPayStatus(PayStatusEnum.CREATE.getStatus());

        //支付金额
        oi.setPayAmount(good.getPrice());
        //商品纸条数量
        oi.setPaperNum(good.getPaperNum());
        //商品ID
        oi.setGoodId(good.getId());
        //商品名称
        oi.setGoodName(good.getGoodName());

        //假如是开店
        if(oi.getOrderType()== OrderTypeEnum.KAI_TONG_DIAN_PU.getStatus()){
            BiShop shop = null;
            if(dto.getShop()!=null && dto.getShop().getId()!=null){
                shop = biShopService.selectBiShopById(dto.getShop().getId());
            }else {
                shop = dto.getShop();
                /** 推荐店铺id */
                shop.setRecommendShopId(oi.getRecommendShopId() + "");
                /** 可提现金额 */
                shop.setShopCashFee(BigDecimal.ZERO);
                /** 累计总金额 */
                shop.setShopTotalFee(BigDecimal.ZERO);
                /** 状态 */
                shop.setStatus(DataStatusEnum.WAIT_PASS.getStatus());
                /** 分佣比例，百分之多少，不能大于100 */
                BigDecimal percentage = friendsConfig.getCommissionRate().multiply(new BigDecimal(100));
                shop.setPercentage(percentage);

                shop.setPassword(Md5Utils.hash(dto.getShop().getPassword()));

                biShopService.insertBiShop(shop);
            }

            if(shop==null){
                throw new Exception("店铺信息错误");
            }
            //设置订单对应的店铺id，支付回调时有用
            oi.setShopId(shop.getId());
        }

        this.insertBiOrderInfo(oi);

        CreateOrderRespDTO respDTO = new CreateOrderRespDTO();
        respDTO.setOrderNo(oi.getMchPayOrderNo());

        if(payFlag) {
            // response包含了调起支付所需的所有参数，可直接用于前端调起支付
            PrepayWithRequestPaymentResponse response = wxPayService.createPayPreOrder(oi);
            if (response != null) {
                respDTO.setParas(response);
                respDTO.setNeedPayFlag(1);
                respDTO.setSaveSuccessFlag(Boolean.TRUE);
                return respDTO;
            } else {
                BiOrderInfo tempOi = new BiOrderInfo();
                tempOi.setId(oi.getId());
                tempOi.setPayStatus(PayStatusEnum.CANCEL.getStatus());
                biOrderInfoMapper.updateBiOrderInfo(tempOi);
                respDTO.setSaveSuccessFlag(Boolean.FALSE);
                respDTO.setSaveFailMsg("调取支付失败，请重试");
                return respDTO;
            }
        }else{
            //不需要支付
            respDTO.setNeedPayFlag(0);
            respDTO.setSaveSuccessFlag(Boolean.TRUE);
            return respDTO;
        }
    }

    @Override
    public CountInfoRespDTO indexCount(BigDecimal profitRate,Integer payStatus, Date begin, Date end) {
        return biOrderInfoMapper.indexCount(profitRate,payStatus,begin,end);
    }

    private String getOrderNo(String openid){
        return Md5Utils.hash(openid+String.valueOf(System.currentTimeMillis()));
    }
}
